package cn.com.gzheroli.bfw.web.system.controler.core;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.gzheroli.auth.service.TSDataruleService;
import cn.com.gzheroli.bfw.bean.LockInfo;
import cn.com.gzheroli.bfw.pojo.base.TSBaseUser;
import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSFunction;
import cn.com.gzheroli.bfw.pojo.base.TSRole;
import cn.com.gzheroli.bfw.pojo.base.TSRoleFunction;
import cn.com.gzheroli.bfw.pojo.base.TSRoleUser;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.common.UploadFile;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboBox;
import cn.com.gzheroli.core.common.model.json.ValidForm;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.ListtoMenu;
import cn.com.gzheroli.core.util.LogUtil;
import cn.com.gzheroli.core.util.MyBeanUtils;
import cn.com.gzheroli.core.util.MyClassLoader;
import cn.com.gzheroli.core.util.PasswordUtil;
import cn.com.gzheroli.core.util.RoletoJson;
import cn.com.gzheroli.core.util.SetListSort;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.rabbitmq.service.log.LogService;
import cn.com.gzheroli.service.bfw.DepartService;
import cn.com.gzheroli.service.bfw.RoleService;
import cn.com.gzheroli.service.bfw.UserService;
import cn.com.gzheroli.tag.core.DataGrid;
import cn.com.gzheroli.tag.vo.datatable.DataTableReturn;
import cn.com.gzheroli.tag.vo.datatable.DataTables;
import cn.com.gzheroli.util.TagUtil;

/**
 * @ClassName: UserController
 * @Description: TODO(用户管理处理类)
 */
@Controller
@RequestMapping("/userController")
public class UserController {
	/**
	 * Logger for this class
	 */
	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(UserController.class);
	private static Integer lockType=Calendar.MINUTE;
	private static Integer lockNum=60;
	@Autowired
	private UserService userService;
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
    private SpringRedisCache cache;
	
	@Autowired
	private DepartService departService;
	
	@Autowired
	private RoleService roleService;
	@Autowired
	private CommonService commonService;
	
	private String message = null;

	@Autowired
	  private TSDataruleService dataruleService;



	/**
	 * 用户列表页面跳转
	 * 
	 * @return
	 *  
	 */
	@RequestMapping(params = "user")
	public ModelAndView user(HttpServletRequest request) {
		// 给部门查询条件中的下拉框准备数据
		String id = request.getParameter("id") == null ? "" : request
				.getParameter("id");
		TSUser retObj = null;
		if (!id.equals(""))
			retObj = userService.getTSUser(id);
		request.setAttribute("user", retObj);
		return new ModelAndView("system/user/userList");
	}
	/**
	 * 获取用户信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "getUserData")
	@ResponseBody
	public AjaxJson getUserData(HttpServletRequest request) {
		AjaxJson j=new AjaxJson();
		// 给部门查询条件中的下拉框准备数据
		String id = request.getParameter("id") == null ? "" : request
				.getParameter("id");
		TSUser retObj = null;
		if (!id.equals("")){
			retObj = userService.getTSUser(id);
			if(retObj.getPartDept()!=null&&!retObj.getPartDept().trim().equals("")){
				String partids=retObj.getPartDept()==null?"":retObj.getPartDept();
				if(partids.endsWith(","))
					partids=partids.substring(0, partids.lastIndexOf(","));
				if(!partids.trim().equals("")){
					String partDeptName=userService.getPartDeptNames(partids);
					retObj.setPartDeptName(partDeptName);
				}else{
					retObj.setPartDeptName("");
				}
			}
		}
			
		j.setObj(retObj);
		j.setSuccess(true);
		j.setMsg("获取成功");
		return j;
	}

	/**
	 * 用户信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "userinfo")
	public String userinfo(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user =cache.getCache(request.getSession().getId(), Client.class).getUser();
		String token = request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		TSUser user = client.getUser();
		request.setAttribute("user", user);
		return "system/user/userinfo";
	}

	/**
	 * 修改密码
	 * 
	 * @return
	 */
	@RequestMapping(params = "changepassword")
	public String changepassword(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user =cache.getCache(request.getSession().getId(), Client.class).getUser();
		String token = request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		TSUser user = client.getUser();
		request.setAttribute("user", user);
		return "system/user/changepassword";
	}

	/**
	 * 修改密码
	 * 
	 * @return
	 */
	@RequestMapping(params = "resetPassword")
	public String resetPassword(HttpServletRequest request) {
		String id = oConvertUtils.getString(request.getParameter("id"));
		TSUser user = userService.getUserById(id);
		request.setAttribute("user", user);
		return "system/user/resetPassword";
	}

	/**
	 * 修改密码
	 * 
	 * @return
	 */
	@RequestMapping(params = "savenewpwd")
	@ResponseBody
	public AjaxJson savenewpwd(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user =cache.getCache(request.getSession().getId(), Client.class).getUser();
		String token = request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		TSUser user = client.getUser();
		String resetPassword = oConvertUtils.getString(request
				.getParameter("userResetPassword"));
		String id = oConvertUtils.getString(request.getParameter("id"));
		String password = oConvertUtils.getString(request
				.getParameter("password"));
		if (resetPassword.equals("true")) {
			TSUser resetUser = userService.getUserById(id);
			resetUser.setPassword(PasswordUtil.encrypt(resetUser.getUserName(),
					password, PasswordUtil.getStaticSalt()));
			commonService.updateEntitie(resetUser, TSBaseUser.class);
			j.setMsg("修改成功");
		} else {
			String newpassword = oConvertUtils.getString(request
					.getParameter("newpassword"));
			String pString = PasswordUtil.encrypt(user.getUserName(), password,
					PasswordUtil.getStaticSalt());
			if (!pString.equals(user.getPassword())) {
				j.setMsg("原密码不正确");
				j.setSuccess(false);
			} else {
				try {
					user.setPassword(PasswordUtil.encrypt(user.getUserName(),
							newpassword, PasswordUtil.getStaticSalt()));
				} catch (Exception e) {
					e.printStackTrace();
				}
				commonService.updateEntitie(user, TSBaseUser.class);
				j.setMsg("修改成功");

			}
		}

		return j;
	}

	/**
	 * 得到角色列表
	 * 
	 * @return
	 */
	@RequestMapping(params = "role")
	@ResponseBody
	public List<ComboBox> role(HttpServletResponse response,
			HttpServletRequest request, ComboBox comboBox) {
		String userId = request.getParameter("id");
		return roleService.getRoleList(userId);
	}

	/**
	 * 得到部门列表
	 * 
	 * @return
	 */
	@RequestMapping(params = "depart")
	@ResponseBody
	public List<ComboBox> depart(HttpServletResponse response,
			HttpServletRequest request, ComboBox comboBox) {
		String id = request.getParameter("id");
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		List<TSDepart> departs = new ArrayList();
		if (StringUtil.isNotEmpty(id)) {
			TSUser user = commonService.get(TSUser.class, id);
			if (user.getDepartId() != null) {
				TSDepart depart = commonService.get(TSDepart.class, user.getDepartId());
				departs.add(depart);
			}
		}
		List<TSDepart> departList = commonService.loadAll(TSDepart.class);
		comboBoxs = TagUtil.getComboBox(departList, departs, comboBox);
		return comboBoxs;
	}

	/**
	 * easyuiAJAX用户列表请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(TSUser user, HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			return ;
		}
		TSUser curUser=client.getUser();
		// 上面的是用的hibernate
		Integer page =request.getParameter("page")==null?1:Integer.parseInt(request.getParameter("page"));
		Integer rows =request.getParameter("rows")==null?20:Integer.parseInt(request.getParameter("rows"));
		Integer start = Integer
				.valueOf((page.intValue() - 1) * rows.intValue()) + 1;
		Integer end = Integer.valueOf(page.intValue() * rows.intValue());
		
		HashMap parameter = new HashMap();
		String mobilePhone = request.getParameter("mobilePhone");
		String officePhone = request.getParameter("officePhone");
		String userName = request.getParameter("userName");
		String realName = request.getParameter("realName");
		String departName = request.getParameter("departName");
		String vipId = request.getParameter("vipId");
		parameter.put("vipId", vipId);
		parameter.put("departName", departName);
		parameter.put("userName", userName);
		parameter.put("realName", realName);
		parameter.put("mobilePhone", mobilePhone);
		parameter.put("officePhone", officePhone);
		parameter.put("maxResults", end.intValue());
		parameter.put("firstResult", start.intValue());
		parameter.put("beginRow", (page-1)*rows);//mysql
		parameter.put("pageSize", end.intValue() - start.intValue() + 1);
		if(departName!=null&&!departName.trim().equals("")){
			List departIdList=departService.getAllSubDeptIds(departName, new ArrayList());
			parameter.put("departIdList", departIdList);
		}
		//String authUserSql=dataruleService.genSqlByModuleName("authUserSql","tu",curUser);	
		//parameter.put("authUserSql", authUserSql);
		Long Acount = userService.selectUserAcount(parameter);
		//dataGrid.setResults(usermapper);
		dataGrid.setTotal(Acount.intValue());
		List<TSUser> userList=userService.getUserList(parameter);
		dataGrid.setResults(userList);
		TagUtil.datagrid(response, dataGrid);// 把数据通过标签返回
		
		//return dataGrid;
	}

	/**
	 * 用户信息录入和更新
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TSUser user, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if ("admin".equals(user.getUserName())) {
			message = "超级管理员[admin]不可删除";
			j.setMsg(message);
			return j;
		}
		/*SQL sql=new SQL();
		sql.SELECT("*");
		sql.FROM("T_S_BASE_USER bu");
		sql.FROM("T_S_USER u");
		sql.WHERE("u.ID=bu.ID and bu.STATUS='1'");
		sql.WHERE("u.id=#{id}");*/
		//user = commonService.get(TSUser.class, user.getId());
		List<TSRoleUser> roleUser = commonService.findByProperty(
				TSRoleUser.class, "userId", user.getId());
		user=commonService.get(TSUser.class, user.getId());
		if (!user.getStatus().equals(Globals.User_ADMIN)) {
			if (roleUser!=null&&!roleUser.isEmpty()&&roleUser.size() > 0) {
				// 删除用户时先删除用户和角色关系表
				//delRoleUser(user);
				for (TSRoleUser tRoleUser : roleUser) {
					commonService.delete(TSRoleUser.class,tRoleUser.getId());
				}
				//commonService.delete(TSUser.class,user.getId());
				commonService.executeSQL("delete from T_S_USER where ID='"+user.getId()+"'");
				commonService.executeSQL("delete from T_S_BASE_USER where ID='"+user.getId()+"'");
				message = "用户：" + user.getUserName() + "删除成功";
				logService.addLogRoleauth(message, Globals.Log_Type_DEL,null,LogUtil.logReqMap(request));
			} else {
				//commonService.delete(TSUser.class,user.getId());
				commonService.executeSQL("delete from T_S_USER where ID='"+user.getId()+"'");
				commonService.executeSQL("delete from T_S_BASE_USER where ID='"+user.getId()+"'");
				message = "用户：" + user.getUserName() + "删除成功";
			}
		} else {
			message = "超级管理员不可删除";
		}

		j.setMsg(message);
		return j;
	}

	public void delRoleUser(TSUser user) {
		// 同步删除用户角色关联表
		List<TSRoleUser> roleUserList = commonService.findByProperty(
				TSRoleUser.class, "userId", user.getId());
		if (roleUserList!=null&&!roleUserList.isEmpty()&&roleUserList.size() >= 1) {
			for (TSRoleUser tRoleUser : roleUserList) {
				commonService.delete(TSRoleUser.class,tRoleUser.getId());
			}
		}
	}

	/**
	 * 检查用户名
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "checkUser")
	@ResponseBody
	public ValidForm checkUser(HttpServletRequest request) {
		ValidForm v = new ValidForm();
		String userName = oConvertUtils
				.getString(request.getParameter("param"));
		String code = oConvertUtils.getString(request.getParameter("code"));
		List<TSUser> roles = commonService.findByProperty(TSUser.class,
				"userName", userName);
		if (roles.size() > 0 && !code.equals(userName)) {
			v.setInfo("用户名已存在");
			v.setStatus("n");
		}
		return v;
	}

	/**
	 * 用户录入
	 * 
	 * @param user
	 * @param req
	 * @return
	 */

	@RequestMapping(params = "saveUser")
	@ResponseBody
	public AjaxJson saveUser(HttpServletRequest request, TSUser user) {
		AjaxJson j = new AjaxJson();
		// 得到用户的角色
		String roleid = oConvertUtils.getString(request.getParameter("roleid"));
		String password = oConvertUtils.getString(request.getParameter("password"));
		if (StringUtil.isNotEmpty(user.getId())) {
			SQL sql=new SQL();
			sql.SELECT("bu.*,u.*");
			sql.FROM("T_S_BASE_USER bu");
			sql.FROM("T_S_USER u");
			sql.WHERE("u.ID=bu.ID and bu.STATUS='1'");
			sql.WHERE("u.id=#{id}");
			//TSUser users = commonService.get(TSUser.class, user.getId());
			//TSBaseUser baseUsers = commonService.get(TSBaseUser.class, user.getId());
			Map para=new HashMap();
			para.put("id", user.getId());
			TSUser users =commonService.findOneObjForJdbc(sql.toString(), para, TSUser.class);
			users.setEmail(user.getEmail());
			users.setVipId(user.getVipId());
			users.setOfficePhone(user.getOfficePhone());
			users.setMobilePhone(user.getMobilePhone());
			//users.setTSDepart(user.getTSDepart());
			if(user.getDepartId()!=null&&!user.getDepartId().trim().equals(""))
				users.setDepartId(user.getDepartId());
			users.setRealName(user.getRealName());
			users.setInterPhone(user.getInterPhone());
			users.setLocation(user.getLocation());
			if(user.getPartDept()!=null&&!user.getPartDept().trim().equals(""))
			users.setPartDept(user.getPartDept());
			users.setStatus(Globals.User_Normal);
			users.setActivitiSync(user.getActivitiSync());
			users.setPartJob(user.getPartJob());
			users.setFax(user.getFax());
			users.setWxId(user.getWxId());
			users.setKtpUserId(user.getKtpUserId());
			// users.setWage(user.getWage());
			/*try {
				MyBeanUtils.copyBeanNotNull2Bean(baseUsers,users);
			} catch (Exception e) {
				e.printStackTrace();
			}*/
			if(users!=null&&users.getUserName()!=null){
				commonService.update(users);
				//commonService.updateEntitie(users,TSBaseUser.class);
				message = "用户: " + users.getRealName() + "更新成功";
				logService.addLogRoleauth(message, Globals.Log_Type_UPDATE,null,LogUtil.logReqMap(request));
			}
			
			/*List<TSRoleUser> ru = systemService.findByProperty(
					TSRoleUser.class, "TSUser.id", user.getId());
			systemService.deleteAllEntitie(ru);*/
			/*systemService.executeSQL("delete from T_S_ROLE_USER  where USER_ID='"+user.getId()+"'");
			message = "用户: " + users.getUserName() + "更新成功";
			if (StringUtil.isNotEmpty(roleid)) {
				saveRoleUser(users.getId(), roleid);
			}*/
			
		} else {
			//TSBaseUser users = commonService.findUniqueByProperty(TSBaseUser.class,"userName", user.getUserName());
			/*SQL sql=new SQL();
			sql.SELECT("bu.*,u.*");
			sql.FROM("T_S_BASE_USER bu");
			sql.FROM("T_S_USER u");
			sql.WHERE("u.ID=bu.ID and bu.STATUS='1'");
			sql.WHERE("bu.USER_NAME=#{userName}");*/
			String sql="select bu.*,u.* from T_S_BASE_USER bu,T_S_USER u";
			sql=sql+" where u.ID=bu.ID and bu.STATUS='1' and bu.USER_NAME=#{userName}";
			Map para=new HashMap();
			para.put("userName", user.getUserName());
			List users=commonService.findByQueryString(sql, TSUser.class, para);
			//TSUser users = commonService.findOneObjForJdbc(sql.toString(), para, TSUser.class);
			if (users != null&&!users.isEmpty()) {
				message = "用户: " + user.getRealName() + "已经存在";
			} else {
				user.setPassword(PasswordUtil.encrypt(user.getUserName(),
						password, PasswordUtil.getStaticSalt()));
				if (user.getDepartId().equals("")) {
					user.setDepartId("");
				}
				user.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
				user.setStatus(Globals.User_Normal);
				
				TSBaseUser baseUsers=new TSBaseUser();
				try {
					MyBeanUtils.copyBeanNotNull2Bean(user,baseUsers);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(baseUsers!=null&&baseUsers.getUserName()!=null){
					//commonService.save(baseUsers);
					commonService.save(user);
					message = "用户: " + baseUsers.getRealName() + "添加成功";
					logService.addLogRoleauth(message, Globals.Log_Type_INSERT,null,LogUtil.logReqMap(request));
				}
				
				
			}

		}
		j.setMsg(message);

		return j;
	}
	@RequestMapping(params = "saveUserRole")
	@ResponseBody
	public  AjaxJson saveUserRole(String userId, String roleidstr,String departId,String departName) {
		AjaxJson j = new AjaxJson();
		String[] roleids = roleidstr.split(",");
		for (int i = 0; i < roleids.length; i++) {
			if (roleids[i] != null && !roleids[i].trim().equals("")) {
				TSRoleUser rUser = new TSRoleUser();
				//TSRole role = systemService.getEntity(TSRole.class, roleids[i]);
				String roleId=roleids[i];
				/*rUser.setTSRole(role);
				rUser.setTSUser(user);*/
				rUser.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
				rUser.setRoleId(roleId);
				rUser.setUserId(userId);
				rUser.setDepartId(departId);
				rUser.setDepartName(departName);
				commonService.save(rUser);
			}
		}
		j.setSuccess(true);
		message="保存成功";
		j.setMsg(message);

		return j;
	}
	@RequestMapping(params = "delUserRole")
	@ResponseBody
	public  AjaxJson delUserRole(String id) {
		AjaxJson j = new AjaxJson();
		commonService.delete(TSRoleUser.class, id);
		j.setSuccess(true);
		message="删除成功";
		j.setMsg(message);

		return j;
	}

	/**
	 * 用户选择角色跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "roles")
	public String roles() {
		return "system/user/users";
	}
	@RequestMapping(params = "roles2")
	public String roles2() {
		return "system/user/users2";
	}
	/**
	 *获取用户未拥有的角色列表
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "selRoleData")
	public void selRoleData(HttpServletRequest request,HttpServletResponse response, DataGrid dataGrid) {
		Integer page =request.getParameter("page")==null?1:Integer.parseInt(request.getParameter("page"));
		Integer rows =request.getParameter("rows")==null?20:Integer.parseInt(request.getParameter("rows"));
		Integer start = Integer
				.valueOf((page.intValue() - 1) * rows.intValue()) + 1;
		Integer end = Integer.valueOf(page.intValue() * rows.intValue());
		String userId=request.getParameter("userId");
		String roleCode=request.getParameter("roleCode");
		String roleName=request.getParameter("roleName");
		Map datamap=new HashMap();
		datamap.put("userId", userId);
		
		datamap.put("roleCode", roleCode);
		datamap.put("roleName", roleName);
		List<Map<String,Object>> userRoleList=roleService.getUserNotRoles(datamap,page,rows);
		Long count=roleService.getUserNotRolesCount(datamap);
		dataGrid.setResults(userRoleList);
		dataGrid.setTotal(count.intValue());
		TagUtil.datagrid(response, dataGrid);// 把数据通过标签返回
	}
	@RequestMapping(params = "selRoleList")
	public String selRolelist(HttpServletRequest request,HttpServletResponse response) {
		String userId=request.getParameter("userId");
		request.setAttribute("userId", userId);
		return "system/user/selRoleList";
	}
	@RequestMapping(params = "userRoleData")
	@ResponseBody
	public List<Map<String,Object>>  userRoleData(HttpServletRequest request) {
		String userId=request.getParameter("userId");
		Map datamap=new HashMap();
		datamap.put("userId", userId);
		List<Map<String,Object>> userRoleList=roleService.getUserRoles(datamap);
		return userRoleList;
	}

	@RequestMapping(params = "userRole")
	public String userRole(HttpServletRequest request,HttpServletResponse response) {
		String userId=request.getParameter("userId");
		
		request.setAttribute("userId", userId);
		return "system/user/userRole";
	}

	/**
	 * 角色显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridRole")
	public void datagridRole(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		/*CriteriaQuery cq = new CriteriaQuery(TSRole.class, dataGrid);
		this.systemService.getDataGridReturn(cq, true);*/
		Map datamap=new HashMap();
	 	Integer page = Integer.valueOf(Integer.parseInt(request.getParameter("page")));
	    Integer rows = Integer.valueOf(Integer.parseInt(request.getParameter("rows")));
	    Integer start = Integer.valueOf((page.intValue() - 1) * rows.intValue())+1;
	    Integer end = Integer.valueOf(page.intValue() * rows.intValue() );
		datamap.put("maxResults", end.intValue());
		datamap.put("firstResult", start.intValue());
		datamap.put("pageSize", rows);
		datamap.put("beginRow", (page-1)*rows);//mysql
		datamap.put("rolename", request.getParameter("roleName"));
		List<Map> data=roleService.getRoles(datamap);
		Long Acount=roleService.getRolesAcount(datamap);
		dataGrid.setResults(data);
		dataGrid.setTotal(Acount.intValue());
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * easyuiAJAX请求数据： 用户选择角色列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(TSUser user, HttpServletRequest req) {
		String departid = oConvertUtils.getString(req.getParameter("departid"));
		Map para=new HashMap();
		if (!StringUtil.isEmpty(departid))
			para.put("id", departid);
			para.put("status", "1");
			List departList=departService.getDepartList(para);
			

		if (StringUtil.isNotEmpty(user.getId())) {
			user=userService.getTSUser(user.getId());
			req.setAttribute("user", user);
			idandname(req, user);
		}
		return new ModelAndView("system/user/user2");
		// return new ModelAndView("system/user/user");
	}


	public void idandname(HttpServletRequest req, TSUser user) {
		String roleId = "";
		String roleName = "";
		Map datamap=new HashMap();
		datamap.put("userId", user.getId());
		List<Map<String,Object>> userRoleList=roleService.getUserRoles(datamap);
		if(userRoleList!=null&&!userRoleList.isEmpty())
		for(Map<String,Object> userRole:userRoleList){
			roleId += userRole.get("id") + ",";
			roleName +=userRole.get("roleName") + ",";
		}
		req.setAttribute("id", roleId);
		req.setAttribute("roleName", roleName);

	}

	/**
	 * 根据部门和角色选择用户跳转页面
	 */
	@RequestMapping(params = "choose")
	public String choose(HttpServletRequest request) {
		List<TSRole> roles = commonService.loadAll(TSRole.class);
		request.setAttribute("roleList", roles);
		return "system/membership/checkuser";
	}

	/**
	 * 部门和角色选择用户的panel跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "chooseUser")
	public String chooseUser(HttpServletRequest request) {
		String departid = request.getParameter("departid");
		String roleid = request.getParameter("roleid");
		request.setAttribute("roleid", roleid);
		request.setAttribute("departid", departid);
		return "system/membership/userlist";
	}

	/**
	 * 部门和角色选择用户的用户显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridUser")
	public void datagridUser(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		final String departid = request.getParameter("departid");
		final String roleid = request.getParameter("roleid");
		/*CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
		if (departid.length() > 0) {
			cq.eq("TDepart.departid", oConvertUtils.getInt(departid, 0));
			cq.add();
		}
		String userid = "";
		if (roleid.length() > 0) {
			List<TSRoleUser> roleUsers = systemService.findByProperty(
					TSRoleUser.class, "TRole.roleid",
					oConvertUtils.getInt(roleid, 0));
			if (roleUsers.size() > 0) {
				for (TSRoleUser tRoleUser : roleUsers) {
					userid += tRoleUser.getUserId() + ",";
				}
			}
			cq.in("userid", oConvertUtils.getInts(userid.split(",")));
			cq.add();
		}
		this.systemService.getDataGridReturn(cq, true);*/
		Map para=new HashMap();
		para.put("departid", departid);
		para.put("roleid", roleid);
		final String tableName = new NameHandler().getTableName(TSUser.class.getSimpleName());
		String sql=new SQL(){{
			SELECT("u.*,bu.*");
		    FROM(tableName+" u");
		    INNER_JOIN("T_S_BASE_USER bu on u.ID = bu.ID");
		    INNER_JOIN("T_S_ROLE_USER  ru on u.ID = ru.USER_ID");
		    WHERE("STATUS='1'");
		    if (StringUtil.isNotEmpty(departid)) {
		        WHERE("bu.DEPART_ID=#{departid}");
		    }
		    if (StringUtil.isNotEmpty(roleid)) {
		        WHERE("ru.ROLE_ID=#{roleid}");
		    }
			}}.toString();
		dataGrid=this.commonService.getDataGridReturn(dataGrid,TSUser.class,sql,para,true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 根据部门和角色选择用户跳转页面
	 */
	@RequestMapping(params = "roleDepart")
	public String roleDepart(HttpServletRequest request) {
		List<TSRole> roles = commonService.loadAll(TSRole.class);
		request.setAttribute("roleList", roles);
		return "system/membership/roledepart";
	}

	/**
	 * 部门和角色选择用户的panel跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "chooseDepart")
	public ModelAndView chooseDepart(HttpServletRequest request) {
		String nodeid = request.getParameter("nodeid");
		ModelAndView modelAndView = null;
		if (nodeid.equals("role")) {
			modelAndView = new ModelAndView("system/membership/users");
		} else {
			modelAndView = new ModelAndView("system/membership/departList");
		}
		return modelAndView;
	}

	/**
	 * 部门和角色选择用户的用户显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridDepart")
	public void datagridDepart(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		/*CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		systemService.getDataGridReturn(cq, true);*/
		Map para=new HashMap();

		final String tableName = new NameHandler().getTableName(TSDepart.class.getSimpleName());
		String sql=new SQL(){{
			SELECT("*");
		    FROM(tableName);
			}}.toString();
		dataGrid=this.commonService.getDataGridReturn(dataGrid,TSDepart.class,sql,para,true);
		TagUtil.datagrid(response, dataGrid);
	}


	/**
	 * 用户列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public String index() {
		return "bootstrap/main";
	}

	/**
	 * 用户列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "main")
	public String main() {
		return "bootstrap/test";
	}


	/**
	 * 设置签名跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "addsign")
	public ModelAndView addsign(HttpServletRequest request) {
		String id = request.getParameter("id");
		request.setAttribute("id", id);
		return new ModelAndView("system/user/usersign");
	}

	/**
	 * 用户录入
	 * 
	 * @param user
	 * @param req
	 * @return
	 */

	@RequestMapping(params = "savesign", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson savesign(HttpServletRequest request) {
		UploadFile uploadFile = new UploadFile(request);
		String id = uploadFile.get("id");
		SQL sql=new SQL();
		sql.SELECT("*");
		sql.FROM("T_S_BASE_USER bu");
		sql.FROM("T_S_USER u");
		sql.WHERE("u.ID=bu.ID and bu.STATUS='1'");
		sql.WHERE("u.id=#{id}");
		TSBaseUser user = commonService.get(TSBaseUser.class, id);
		uploadFile.setRealPath("signatureFile");
		uploadFile.setCusPath("signature");
		uploadFile.setByteField("signature");
		uploadFile.setBasePath("resources");
		uploadFile.setRename(false);
		uploadFile.setObject(user);
		AjaxJson j = new AjaxJson();
		message = user.getUserName() + "设置签名成功";
		systemService.uploadFile(uploadFile);
		logService.addLogRoleauth(message, Globals.Log_Type_INSERT,null,LogUtil.logReqMap(request));
		j.setMsg(message);

		return j;
	}



	@RequestMapping(params = "changestyle")
	public String changeStyle(HttpServletRequest request) {
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user =cache.getCache(request.getSession().getId(), Client.class).getUser();
		String token = request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		TSUser user = client.getUser();
		if (user == null) {
			return "login/login";
		}
		String indexStyle = "shortcut";
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			if (cookie == null || StringUtils.isEmpty(cookie.getName())) {
				continue;
			}
			if (cookie.getName().equalsIgnoreCase("INDEXSTYLE")) {
				indexStyle = cookie.getValue();
			}
		}
		request.setAttribute("indexStyle", indexStyle);
		return "system/user/changestyle";
	}

	/**
	 * @Title: saveStyle
	 * @Description: 修改首页样式
	 * @param request
	 * @return AjaxJson
	 * @throws
	 */
	@RequestMapping(params = "savestyle")
	@ResponseBody
	public AjaxJson saveStyle(HttpServletRequest request,
			HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		j.setSuccess(Boolean.FALSE);
		//TSUser user = ResourceUtil.getSessionUserName();
		//TSUser user =cache.getCache(request.getSession().getId(), Client.class).getUser();
		String token = request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		TSUser user = client.getUser();
		if (user != null) {
			String indexStyle = request.getParameter("indexStyle");
			if (StringUtils.isNotEmpty(indexStyle)) {
				Cookie cookie = new Cookie("INDEXSTYLE", indexStyle);
				// 设置cookie有效期为一个月
				cookie.setMaxAge(3600 * 24 * 30);
				response.addCookie(cookie);
				j.setSuccess(Boolean.TRUE);
				j.setMsg("样式修改成功，请刷新页面");
			}
		} else {
			j.setMsg("请登录后再操作");
		}
		return j;
	}

	/**
	 * 根据用户角色获取用户下拉列表串
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "getGroupUserStr")
	@ResponseBody
	public AjaxJson getGroupUserStr(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		// String groupid =
		// StringUtil.getEncodePra(req.getParameter("groupid"));
		String controlid = StringUtil.getEncodePra(request
				.getParameter("controlid"));
		String groupstr = "";
		String roleid = oConvertUtils.getString(request.getParameter("roleid"));
		Map para=new HashMap();
		para.put("roleId", roleid);
		List<TSUser> users = this.userService.getUserListByRole(para);
		if (users.size() > 0) {
			for (TSUser user : users) {
				groupstr += "<option value=\"" + user.getUserName() + "\">"
						+ user.getRealName() + "</option>";
			}
		}
		j.setMsg(groupstr);
		return j;
	}

	/**
	 * 导入文件跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "toMigrate")
	public ModelAndView toCgformMigrate(HttpServletRequest req) {
		return new ModelAndView("system/user/migrateInclude");
	}

	/**
	 * 导入用户信息数据
	 * 
	 * @param request
	 * @param response
	 */
	/*@ResponseBody
	@RequestMapping(params = "doMigrateIn")
	public AjaxJson importUserForExcel(HttpServletRequest request,
			HttpServletResponse response) {
		return userService.importUserForExcel(request, response);
	}*/
	/**
	 * 锁定账户
	
	 * 
	 * @author pu.chen
	 */
	@RequestMapping(params = "lock")
	@ResponseBody
	public AjaxJson lock(String id, HttpServletRequest req) {
		AjaxJson j = new AjaxJson();
		
		TSBaseUser user = commonService.get(TSBaseUser.class, id);
		if("admin".equals(user.getUserName())){
			message = "超级管理员[admin]不可操作";
			j.setMsg(message);
			return j;
		}
		String lockValue=req.getParameter("lockvalue");
		String username=user.getUserName();
		user.setStatus(new Short(lockValue));
		try{
			commonService.updateEntitie(user);
			Map lockUsers=cache.getCache("lockUsers", HashMap.class);
			
			if(lockUsers==null||!lockUsers.containsKey(username)){
    			if(lockUsers==null)
    				lockUsers=new HashMap();
    			LockInfo info=new LockInfo();
    			info.setLockCount(1);
    			info.setUpdateTime(new Date());
    			info.setLockTime(null);
    			lockUsers.put(username, info);
				if(cache.getCache("lockUsers", HashMap.class)==null)
    				cache.putCache("lockUsers", lockUsers);
    			
    		}
			if(lockValue.equals("0")){
    			LockInfo lockInfo=(LockInfo)lockUsers.get(username);
    			Calendar calendar2=Calendar.getInstance();
//				calendar2.add(Calendar.HOUR_OF_DAY, 2);
				calendar2.add(lockType, lockNum);
				Long H2_long=calendar2.getTime().getTime();
				lockInfo.setLockTime( H2_long);
				lockInfo.setUpdateTime(new Date());
				lockUsers.put(username, lockInfo);
    		}else if(lockValue.equals("1")){
				lockUsers.remove(username);
			}
			cache.deleteCache("lockUsers");
			cache.putCache("lockUsers", lockUsers);
		if("0".equals(lockValue)){
			message = "用户：" + user.getUserName() + "锁定成功!";
		}else if("1".equals(lockValue)){
			message = "用户：" + user.getUserName() + "激活成功!";
		}
		logService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO,LogUtil.logReqMap(req));
		}catch(Exception e){
			message = "操作失败!";
		}
		j.setMsg(message);
		return j;
	}
}